package com.easypoi.controller;

import com.easypoi.utils.ExcelUtils;
import com.easypoi.service.PersonServer;
import com.easypoi.entity.Person;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/** @author HKC */
@Controller
public class PersonController {
  @Autowired private PersonServer personServer;

  @RequestMapping("/")
  public String index() {
    return "index";
  }

  @RequestMapping("/import")
  public String importExcel() {
    return "import";
  }

  @RequestMapping("/export")
  public void export(HttpServletResponse response) {
    List<Person> personList = personServer.selectAll();
    ExcelUtils.exportExcel(personList, "用户信息", "用户信息列表", Person.class, "用户信息列表.xls", response);
  }

  @PostMapping("/importExcel")
  public String importExcel(@RequestParam(value = "file") MultipartFile file) {
    List<Person> personList = ExcelUtils.importExcel(file, 1, 1, Person.class);
    System.out.println("共导入了【" + personList.size() + "】行数据");
    for (Person person : personList) {
      String username = person.getUsername();
      String password = person.getPassword();
      Person temp = personServer.findByNameAndPassword(username, password);
      if (temp == null) {
        int res = personServer.saveImport(person);
        if (res != 0 && res > 0) {
          System.out.println("插入成功");
        }
      }
    }
    return "redirect:/show";
  }

  @RequestMapping("/show")
  public String show(Model model, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum) {
//    pageNum = pageNum == 0 ? 1 : pageNum;
    PageHelper.startPage(pageNum, 10);
    List<Person> personList = personServer.selectAll();
    PageInfo<Person> page = new PageInfo<>(personList);
    model.addAttribute("page", page);
    return "show";
  }
}
